import oss2
from django.conf import settings
import tempfile
import os
import logging

logger = logging.getLogger(__name__)


def upload_to_oss(file, file_path):
    """
    上传文件到阿里云 OSS
    :param file: Django UploadedFile 或文件对象
    :param file_path: OSS 中的存储路径
    :return: 完整的文件 URL 或 None
    """
    config = settings.ALIYUN_OSS_CONFIG
    auth = oss2.Auth(config['ACCESS_KEY_ID'], config['ACCESS_KEY_SECRET'])
    bucket = oss2.Bucket(auth, config['ENDPOINT'], config['BUCKET_NAME'])
    try:
        # 如果 file 是 UploadedFile，需要读入 bytes
        data = file.read() if hasattr(file, 'read') else file
        bucket.put_object(file_path, data)
        return f"{config['BUCKET_URL'].rstrip('/')}/{file_path}"
    except Exception as e:
        logger.exception("OSS上传失败")
        return None


def download_from_oss(file_path):
    """
    从阿里云 OSS 下载文件到本地临时文件
    :param file_path: OSS 文件路径
    :return: 本地临时文件路径 或 None
    """
    config = settings.ALIYUN_OSS_CONFIG
    auth = oss2.Auth(config['ACCESS_KEY_ID'], config['ACCESS_KEY_SECRET'])
    bucket = oss2.Bucket(auth, config['ENDPOINT'], config['BUCKET_NAME'])
    try:
        suffix = os.path.splitext(file_path)[1]
        tmp = tempfile.NamedTemporaryFile(delete=False, suffix=suffix)
        bucket.get_object_to_file(file_path, tmp.name)
        return tmp.name
    except Exception as e:
        logger.exception("OSS 下载失败")
        return None
